package com.xxxy.jsq.action.teacher;

import com.xxxy.jsq.dao.TeacherDao;
import com.xxxy.jsq.model.Teacher;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 教师信息更新功能Servlet
 */
@WebServlet("/updateTeacherServlet")
public class updateTeacherServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public updateTeacherServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码，避免中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 创建教师DAO对象
        TeacherDao dao = new TeacherDao();

        // 创建教师模型对象
        Teacher model = new Teacher();

        // 获取页面传递的参数（与前端表单字段名保持一致）
        String teacherId = request.getParameter("cid");           // 教师ID（隐藏字段）
        String teacherName = request.getParameter("cname");       // 教师姓名
        String departmentId = request.getParameter("pdnames");    // 所属部门
        String teacherGender = request.getParameter("tgender");   // 性别
        String teacherPhone = request.getParameter("tphone");     // 联系电话
        String teacherNum = request.getParameter("tnum");         // 教师编号
        String teacherFlag = request.getParameter("cflag");       // 状态

        // 设置模型对象属性
        if (teacherId != null && !teacherId.equals("")) {
            model.setTeacherId(Long.valueOf(teacherId));
        }
        if (teacherName != null && !teacherName.equals("")) {
            model.setTeacherName(teacherName);
        }
        if (departmentId != null && !departmentId.equals("")) {
            model.setDepartmentId(departmentId);
        }
        if (teacherGender != null && !teacherGender.equals("")) {
            model.setTeacherGender(teacherGender);
        }
        if (teacherPhone != null && !teacherPhone.equals("")) {
            model.setTeacherPhone(teacherPhone);
        }
        if (teacherNum != null && !teacherNum.equals("")) {
            model.setTeacherNum(teacherNum);
        }
        if (teacherFlag != null && !teacherFlag.equals("")) {
            model.setTeacherFlag(teacherFlag);
        }

        // 调用DAO层的更新方法
        String result = dao.update(model);

        // 返回处理结果给前端
        PrintWriter out = response.getWriter();
        out.print(result);  // 返回"Ok"表示成功，"Err"表示失败，"Same"表示名称重复
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // POST请求也交给doGet处理
        doGet(request, response);
    }
}